package com.hooda;

import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @author zhangzp
 * @version 1.0, 2021/10/18
 */
public class ConsistentHashNoVirtual {

    public static void main(String[] args) {
        // 初始化： 把服务器节点IP的hash值对应到hash环上
        String[] tomcatServers = new String[] {"123.111.0.0", "123.101.3.1", "111.20.35.2", "123.98.26.3"};
        SortedMap<Integer, String> hashServerMap = new TreeMap<Integer, String>();

        for (String tomcatServer : tomcatServers) {
            // 求出每一个ip的hash值，对应到hash环上，存储hash值与ip的对应关系
            int serverHash = Math.abs(tomcatServer.hashCode());
            hashServerMap.put(serverHash, tomcatServer);
        }
        // 针对客户端IP求出hash值
        // 定义客户端IP
        String[] clients = new String[] {"10.78.12.3", "113.25.63.1", "126.12.3.8"};
        for (String client : clients) {
            // 针对客户端，找到能够处理当前客户端请求的服务器
            int clientHash = Math.abs(client.hashCode());
            // 根据客户端IP的hash值去找到哪一个服务器节点能够处理
            SortedMap<Integer, String> integerStringSortedMap = hashServerMap.tailMap(clientHash);
            Integer firstKey;
            if (integerStringSortedMap.isEmpty()) {
                firstKey = hashServerMap.firstKey();
            } else {
                firstKey = integerStringSortedMap.firstKey();
            }
            System.out.println("=========>>>>客户端：" + client + " 被路由到服务器：" + hashServerMap.get(firstKey));
        }

    }
}
